#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-09-06 14:32:57
# @Author  : yangchaojun (YYChildren@gmail.com)
# @Link    : https://git.mingchao.com/yangchaojun
# @Version : 

from flask import Flask, request, send_from_directory, send_file, jsonify
from mtweb.utils import  db
from mtweb.utils.config import CONFIG
import json

app = Flask(__name__, static_url_path='')

@app.route('/', methods=['GET'])
def index():
    return send_file('static/index.html')

@app.route('/static/<path:path>', methods=['GET'])
def send_static(path):
    return send_from_directory('static', path)

@app.route('/comment_summary/<int:limit>/<int:offset>', methods=['GET'])
def get_comment_summary(limit, offset):
    database = CONFIG['comment_summary:database'] 
    table = CONFIG['comment_summary:table']
    fields = ['game_id', 'game_name', 'summaries']
    ja = db.get_record(database, table, fields, limit, offset)
    for c in ja:
        c['summaries'] = json.loads(c['summaries'])
    return jsonify(ja)

@app.route('/search_comment_summary/<int:limit>/<search_game>', methods=['GET'])
def search_comment_summary(limit, search_game):
    database = CONFIG['comment_summary:database'] 
    table = CONFIG['comment_summary:table']
    fields = ['game_id', 'game_name', 'summaries']
    fs = ",".join(fields)
    sql = "SELECT %s FROM %s.%s WHERE game_name like '%%%s%%' limit %s" % (fs, database, table, search_game, limit)
    rs=db.get_record_from_sql(sql)
    for c in rs:
        c['summaries'] = json.loads(c['summaries'])
    return jsonify(rs)

@app.route('/get_remmend_game', methods=['GET'])
def get_remmend_game():
    _ftype = request.args.get('type', 'mobile')
    limit = int(request.args.get('limit', 10))
    page = int(request.args.get('page', 1))
    sql = """
    SELECT c.no,c.source,c.game_id,c.game_name,c.summaries,d.tags,d.game_logo_url icon FROM
    (SELECT a.no,a.source,a.game_id,a.game_name,b.summaries FROM game_process.c_game_ranking_by_bma_taptap a
    LEFT OUTER JOIN  game_process.c_game_comment_summary b USING(source, game_id)) c 
    LEFT OUTER JOIN game_source.s_game_detail d USING(source, game_id)
    LIMIT %d  OFFSET %d
    """ % (limit, (page - 1) * limit)
    rs = db.get_record_from_sql(sql)
    for r in rs:
        print(r['summaries'])
        r['summaries'] = json.loads(r['summaries']) if r['summaries'] is not None else []
        r['tags'] = r['tags'].split(',') if r['tags'] is not None else []
    return jsonify(rs)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port = 9000)
